package com.genius.workflow.realm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.role.entity.RoleJson;
import com.genius.adminmanager.user.entity.UserJson;
import com.genius.workflow.config.DefaultConfiguration;
import com.genius.workflow.ehcache.CacheUtils;
import com.genius.workflow.ehcache.PowerUtil;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools2;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.PasswordMD5;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import java.sql.SQLException;

/**
 * 自定义Realm
 * @author woy
 *
 */
public class PlatformRealm extends AuthorizingRealm{

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		JSONObject userJson = (JSONObject) SecurityUtils.getSubject().getPrincipal();

		String userId = userJson.getString(UserJson.userId);
		if(!CacheUtils.cacheUtils().getCacheManager().cacheExists(userId)){
			Session session = SecurityUtils.getSubject().getSession();
			String currentRoleID = (String)session.getAttribute(RoleJson.roleId);
			PowerUtil.doGetAuthorizationInfo(session,currentRoleID);
		}
		SimpleAuthorizationInfo info= (SimpleAuthorizationInfo)CacheUtils.cacheUtils().getElement(userId, DefaultConfiguration.AuthorizationInfo);
		if(info == null){
			Session session = SecurityUtils.getSubject().getSession();
			String currentRoleID = (String)session.getAttribute(RoleJson.roleId);
			PowerUtil.doGetAuthorizationInfo(session,currentRoleID);
			info= (SimpleAuthorizationInfo)CacheUtils.cacheUtils().getElement(userId, DefaultConfiguration.AuthorizationInfo);
		}
		
		return info;
	}

	/**
	 * 权限认证
				*/
		@Override
		protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
			UsernamePasswordToken userToken = (UsernamePasswordToken) token;
			//判断账号密码是否相同
			boolean userpass = userToken.getUsername().equals(String.valueOf(userToken.getPassword()));
			String tiaojian = "username=?";
			if(userpass){
				tiaojian = "userId = ?";
			}
			String userName=(String)token.getPrincipal();
			//User user=userRepository.findByUserName(userName);
			JSONObject response = new JSONObject();
			String field = UserJson.userId+","+UserJson.username+","+UserJson.password+","+UserJson.name
					+","+UserJson.command+","+UserJson.groupId+","+UserJson.jobnumber;
			String sql = "select "+field+" from t_user where "+tiaojian+" and status=1";
			try {
				String [] parms = new String[]{userName};
				JSONObject userJson = DBTools2.select(sql,parms);
				if(userJson != null ){
					ByteSource salt = ByteSource.Util.bytes(userName);
					AuthenticationInfo authcInfo=null;
					if(userpass){
						authcInfo = new SimpleAuthenticationInfo(userJson,PasswordMD5.MD5Pwd(userName, userName),salt,getName());
					}else{
						authcInfo = new SimpleAuthenticationInfo(userJson,userJson.getString(UserJson.password),salt,getName());

					}
					return authcInfo;
				}else{
					return null;
				}
			}catch (ConnectionException e) {
				response.put(ResponseJson.status, ResponseJson.status_Failed);
	    		response.put(ResponseJson.msg, ResponseJson.msg_No_Porwer_Query_Field);
			} catch (DBClosedException e) {
				response.put(ResponseJson.status, ResponseJson.status_Failed);
	    		response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
			} catch (SQLException e) {
				response.put(ResponseJson.status, ResponseJson.status_Failed);
				response.put(ResponseJson.msg, ResponseJson.msg_Del_Data_Error);
			}
			return null;
	}

}
